﻿CREATE FUNCTION [QIC].[CallFactory_VUPDATE](@Token QIC.TokenTable READONLY, @CallerId INT, @CalleeId INT, @ReturnPropertName VARCHAR(50), @TokenMap VARCHAR(50), @Indent INT, @CalleeDelegateName varchar(50))
RETURNS VARCHAR(MAX)
AS
BEGIN

	DECLARE @Call VARCHAR(MAX) 
	DECLARE @UpdateSQL VARCHAR(MAX)
	DECLARE @Keys TABLE (CallerPropertyName varchar(50), CalleePropertyName varchar(50))	
	DECLARE @TargetToken QIC.TokenTable
	DECLARE @LocalToken QIC.TokenTable
	DECLARE @CalleeView VARCHAR(MAX)
	DECLARE @KeySQL VARCHAR(MAX)	

	SET @KeySQL = ''
	SET @UpdateSQL = ''

	INSERT INTO @TargetToken (IsOutPut,IsReadOnly,MaxLength,ObjectId,Precision,PropertyId,PropertyName,Scale,UserTypeId)
	SELECT 0,0,0,token.ObjectId,0,token.PropertyId,token.PropertyName,0,0 FROM @Token token
	INNER JOIN sys.columns Targetcolumns
		ON Targetcolumns.object_id = token.ObjectId
		AND Targetcolumns.column_id = token.PropertyId
		AND Targetcolumns.is_computed = 0
		AND Targetcolumns.is_identity = 0
	WHERE token.ObjectId = @CalleeId


	INSERT INTO @LocalToken (IsOutPut,IsReadOnly,MaxLength,ObjectId,Precision,PropertyId,PropertyName,Scale,UserTypeId)
	SELECT 0,0,0,ObjectId,0,PropertyId,PropertyName,0,0 FROM @Token 
	WHERE ObjectId = @CallerId OR (PropertyName LIKE '@%') OR (PropertyName LIKE '''%''')

	SELECT @CalleeView = QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(name) from sys.objects WHERE object_id = @CalleeId
	
	INSERT INTO @Keys (CallerPropertyName,CalleePropertyName)
	SELECT CallerPropertyName,CalleePropertyName FROM QIC.KeyResolve_(@Token, @CallerId, @CalleeId, @TokenMap)

	SELECT @UpdateSQL += 
		QUOTENAME(targetToken.PropertyName) + 
		'= ' + CASE LEFT(QIC.TokenSubstitute(@LocalToken, targetToken.PropertyName, @TokenMap),1) WHEN '@' THEN '' WHEN '''' THEN '' ELSE 'inserted.' END  + 
		QIC.TokenSubstitute(@LocalToken, targetToken.PropertyName, @TokenMap) + ', ' 
	FROM @TargetToken targetToken
	LEFT OUTER JOIN @Token sourceToken
		ON sourceToken.ObjectId = @CallerId
		AND QIC.TokenSubstitute(@LocalToken, sourceToken.PropertyName, @TokenMap) =  targetToken.PropertyName
	WHERE NOT EXISTS (select * from @Keys keys where keys.CallerPropertyName = targetToken.PropertyName)

	SELECT @KeySQL += @CalleeView + '.' + QUOTENAME(CallerPropertyName) + ' = inserted.' + QUOTENAME(CalleePropertyName) + ' AND ' FROM @Keys

	IF LEN(@KeySQL) > 0 AND LEN(@UpdateSQL) > 0
	BEGIN
		SET @KeySQL = LEFT(@KeySQL, DATALENGTH(@KeySQL) - DATALENGTH(' AND '))
		SET @UpdateSQL = LEFT(@UpdateSQL, DATALENGTH(@UpdateSQL) - DATALENGTH(', '))

		SET @Call = ''
		SET @Call += 
			QIC.Indent(@Indent) + 'UPDATE ' + @CalleeView + ' SET ' + @UpdateSQL + QIC.LB() +
			QIC.Indent(@Indent) + 'FROM inserted'  + QIC.LB() +
			QIC.Indent(@Indent) + 'WHERE ' + @KeySQL

	END

	RETURN @Call	

END